//
//  PBHomeDetailController.m
//  PBHomeDemo
//
//  Created by Playboy on 2017/11/21.
//  Copyright © 2017年 tmkj. All rights reserved.
//

#import "PBHomeDetailController.h"
#import "UIColor+Hex.h"
#import "PBHomeDetailTopCell.h"
#import "PBHomeSettingCell.h"
#import "PBHomeDesCell.h"
#import "PBHomeDetailModel.h"
#import "PBOrderHomeController.h"
#import "PBChoosePayTypeController.h"
#import "PBHomeNearCell.h"
#import "PBHomeNearDetailCell.h"
#import "JCAlertView.h"
#import "PBVerifyInfoController.h"
#import "PBComfimHomeController.h"

#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define WIDTH_SCALE (SCREEN_WIDTH/320.f)
#define HEIGHT_SCALE  (SCREEN_HEIGHT/568.f)

static NSString * const kPBHomeDetailTopCell = @"PBHomeDetailTopCell";
static NSString * const kPBHomeSettingCell   = @"PBHomeSettingCell";
static NSString * const kPBHomeDesCell       = @"PBHomeDesCell";
static NSString * const kPBHomeNearCell      = @"PBHomeNearCell";
static NSString * const kPBHomeNearDetailCell = @"PBHomeNearDetailCell";

@interface PBHomeDetailController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIButton *bookRoomButton;
@property (strong, nonatomic) IBOutlet UIButton *nowButton;
@property (strong, nonatomic) IBOutlet UILabel *tipLabel;
@property (weak, nonatomic) UIImageView *backImageView;
@property (nonatomic, strong) PBHomeDetailModel    *detailModel;
@property (nonatomic, strong) UIBarButtonItem *rightItem;
@property (nonatomic, strong) JCAlertView   *alert;
@end

@implementation PBHomeDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configure];
}
- (void)configure {
    [self configureView];
    [self configureData];
}
- (void)configureView {
    [self.tableView registerNib:[UINib nibWithNibName:kPBHomeDetailTopCell bundle:nil] forCellReuseIdentifier:kPBHomeDetailTopCell];
    [self.tableView registerNib:[UINib nibWithNibName:kPBHomeSettingCell bundle:nil] forCellReuseIdentifier:kPBHomeSettingCell];
    [self.tableView registerNib:[UINib nibWithNibName:kPBHomeDesCell bundle:nil] forCellReuseIdentifier:kPBHomeDesCell];
    [self.tableView registerNib:[UINib nibWithNibName:kPBHomeNearCell bundle:nil] forCellReuseIdentifier:kPBHomeNearCell];
    [self.tableView registerNib:[UINib nibWithNibName:kPBHomeNearDetailCell bundle:nil] forCellReuseIdentifier:kPBHomeNearDetailCell];
}
- (void)configureData {
    NSDictionary *param = @{@"houseId":self.houseId};
    [self showHud];
    [TMNetwork requestGetWithParam:param url:@"/house/detail" callback:^(TMBaseReqModel *model) {
        [self hideHud];
        if (model.code == 200) {
            self.detailModel = [PBHomeDetailModel objectWithKeyValues:model.data];
            self.rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"detail_like"] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClcik)];
            self.rightItem.tintColor = [UIColor tm_mainOrignColor];
            if (self.detailModel.canCollection == 1) {
                self.rightItem.image = [UIImage imageNamed:@"detail_like"];
            }else {
                self.rightItem.image = [UIImage imageNamed:@"detail_liked"];
            }
            
//            UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareItemClick)];
//            shareItem.tintColor = [UIColor tm_mainOrignColor];
            
            self.navigationItem.rightBarButtonItems = @[self.rightItem];
            [self.tableView reloadData];
            // 判断是否可以签约
            if (self.detailModel.rentStatus == 1) {
                self.bookRoomButton.hidden = NO;
                self.nowButton.hidden = NO;
            }else if (self.detailModel.rentStatus == 2){
                self.bookRoomButton.hidden = YES;
                self.nowButton.hidden = YES;
                self.tipLabel.text = @"房屋已出租";
            }else if (self.detailModel.rentStatus == 3){
                self.bookRoomButton.hidden = YES;
                self.nowButton.hidden = YES;
                self.tipLabel.text = @"房屋已被锁定";
            }
            
        }else {
            [self showHint:model.message];
        }
    }];
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4+self.detailModel.houseTrafficList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        PBHomeDetailTopCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBHomeDetailTopCell forIndexPath:indexPath];
        [cell refreshWithModel:self.detailModel];
        return cell;
    }else if (indexPath.row == 1) {
        PBHomeSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBHomeSettingCell forIndexPath:indexPath];
        [cell refreshWithInfo:self.detailModel.houseConfig];
        return cell;
    }else if (indexPath.row == 2) {
        PBHomeDesCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBHomeDesCell forIndexPath:indexPath];
        [cell refreshWithDes:self.detailModel.periphery];
        return cell;
    }else if (indexPath.row == 3) {
        PBHomeNearCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBHomeNearCell forIndexPath:indexPath]; 
        cell.jumpVC = self;
        [cell refreshWithlongitude:self.detailModel.longitude latitude:self.detailModel.latitude name:self.detailModel.name];
        return cell;
    }
    PBHomeNearDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBHomeNearDetailCell forIndexPath:indexPath];
    [cell refreshWithModel:self.detailModel.houseTrafficList[indexPath.row-4]];
    return cell;
}

// 预约看房
- (IBAction)orderButtonClick:(UIButton *)sender {
    PBOrderHomeController *vc = [[PBOrderHomeController alloc] init];
    vc.model = self.detailModel;
    [self.navigationController pushViewController:vc animated:YES];
}

// 立即签约
- (IBAction)comfimButtonClick:(UIButton *)sender {
    [self showHud];
    [TMNetwork requestGetWithParam:@{} url:@"/user/identifyCard/get" callback:^(TMBaseReqModel *model) {
        [self hideHud];
        if (model.code == 200) {
            if ([model.data[@"state"] integerValue] == 2) {
                PBComfimHomeController *vc = [[PBComfimHomeController alloc] init];
                vc.model = self.detailModel;
                [self.navigationController pushViewController:vc animated:YES];
            }else if ([model.data[@"state"] integerValue] == 1) {
                [self showHint:@"您的资料还在审核中，审核通过后即可签约"];
            }else {
                [self showAlert];
            }
        }else if (model.code == 401) {
            PBLoginViewController *loginVC = [[PBLoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
        }else {
            [self showHint:model.message];
        }
    }];
}

- (void)showAlert {
    // 弹出框背景
    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 80, 140)];
    customView.backgroundColor = [UIColor whiteColor];
    
    // 弹出框标题
    UILabel *titlelabel = [[UILabel alloc] init];
    titlelabel.textAlignment = NSTextAlignmentCenter;
    titlelabel.font = [UIFont systemFontOfSize:13];
    titlelabel.text = @"温馨提示";
    titlelabel.textColor = UIColorWithRGB(255,85,85);
    [customView addSubview:titlelabel];
    [titlelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(20);
    }];
    
    // 温馨提示
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.textAlignment = NSTextAlignmentLeft;
    tipLabel.font = [UIFont systemFontOfSize:13];
    tipLabel.text = @"您还未实名认证，立即前往认证？";
    tipLabel.textColor = [UIColor tm_LabelTextColor];
    [customView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(50);
    }];
    
    // 横线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor tm_separationBgColor];
    [customView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(90);
        make.height.mas_equalTo(1);
    }];
    
    // 取消
    UIButton *cancelButton = [[UIButton alloc] init];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [cancelButton setTitleColor:UIColorWithRGB(153, 153, 153) forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:cancelButton];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo((kScreenWidth - 80)/2);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo (91);
        make.left.mas_equalTo (0);
    }];
    
    // 竖线
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor tm_separationBgColor];
    [customView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo((kScreenWidth - 80)/2);
        make.top.mas_equalTo(101);
        make.width.mas_equalTo(1);
        make.bottom.mas_equalTo(-10);
    }];
    
    // 确定
    UIButton *sureButton = [[UIButton alloc] init];
    [sureButton setTitle:@"去认证" forState:UIControlStateNormal];
    sureButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [sureButton setTitleColor:[UIColor tm_mainOrignColor] forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(sureButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:sureButton];
    [sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo((kScreenWidth - 80)/2);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo (91);
        make.right.mas_equalTo (0);
    }];
    
    self.alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
    self.alert.layer.cornerRadius = 5;
    self.alert.layer.masksToBounds = YES;
    [self.alert show];
}

- (void)cancelButtonClick {
    [self.alert dismiss];
}
- (void)sureButtonClick {
    [self.alert dismiss];
    PBVerifyInfoController *vc = [[PBVerifyInfoController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - super
- (void)resetNavigationBar {
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)resetNavigationBarItems {
    [super resetNavigationBarItems];
    self.title = @"房屋详细情况";
    
}

// 收藏
- (void)rightItemClcik {
    NSDictionary *param = @{@"houseId":self.houseId};
    [TMNetwork requestPostWithParam:param url:@"/house/collection" callback:^(TMBaseReqModel *model) {
        if (model.code == 200) {
            if ([self.rightItem.image isEqual: [UIImage imageNamed:@"detail_like"]]) {
                [self showHint:@"收藏成功"];
                self.rightItem.image = [UIImage imageNamed:@"detail_liked"];
            }else if ([self.rightItem.image isEqual: [UIImage imageNamed:@"detail_liked"]]) {
                [self showHint:@"取消收藏成功"];
                self.rightItem.image = [UIImage imageNamed:@"detail_like"];
            }
        }else if (model.code == 401) {
            PBLoginViewController *loginVC = [[PBLoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
            
        }else {
            [self showHint:model.message];
        }
    }];
}

// 分享
- (void)shareItemClick {
    [self initShareView];
}

/** 初始化分享界面 */
- (void) initShareView{
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
//    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIWindow *window = [TMShareData shareData].window;
    
    //透明蒙层
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    grayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    grayView.tag = 60000;
    UITapGestureRecognizer *tapGrayView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeShareView)];
    [grayView addGestureRecognizer:tapGrayView];
    grayView.userInteractionEnabled = YES;
    [window addSubview:grayView];
    
    //分享控制器
    UIView *shareBackView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 150*HEIGHT_SCALE)];
    shareBackView.backgroundColor =[UIColor whiteColor];
    shareBackView.tag = 60001;
    [window addSubview:shareBackView];
    
    //分享图标和标题数组
    NSArray *imageNameArr = @[@"share_qq",@"share_weixin",@"share_friend",@"share_qzone",@"share_sina"];
    NSMutableArray *imagesArr = [NSMutableArray array];
    for (NSString *imageName in imageNameArr) {
        UIImage *image = [UIImage imageNamed:imageName];
        [imagesArr addObject:image];
    }
    NSArray *titlesArr = @[@"QQ",@"微信",@"朋友圈",@"QQ空间",@"微博"];
    NSMutableArray *titleNameArr = [NSMutableArray array];
    for (NSString *title in titlesArr) {
        [titleNameArr addObject:title];
    }
    //分享按钮
    CGFloat itemWidth = 32;
    CGFloat itemHeight = 32+25;
    CGFloat spaceX = (SCREEN_WIDTH-32*5)/6;
    CGFloat spaceY = 16;
    NSInteger rowCount = 5;
    for (int i =0; i<titleNameArr.count; i++) {
        UIButton *iconBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        iconBtn.frame = CGRectMake(spaceX + (i%rowCount)*(itemWidth+spaceX), 24 + (i/rowCount)*(itemHeight+spaceY), itemWidth, itemWidth);
        [iconBtn setImage:imagesArr[i] forState:UIControlStateNormal];
        iconBtn.tag = 2000 + i;
        [iconBtn addTarget:self action:@selector(shareItemAction:) forControlEvents:UIControlEventTouchUpInside];
        [shareBackView addSubview:iconBtn];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 20)];
        titleLabel.center = CGPointMake(CGRectGetMinX(iconBtn.frame)+itemWidth/2, CGRectGetMaxY(iconBtn.frame)+10);
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.font = [UIFont systemFontOfSize:12.0];
        titleLabel.text = titleNameArr[i];
        [shareBackView addSubview:titleLabel];
    }
    
    if (titleNameArr.count<=5) {
        shareBackView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 150*HEIGHT_SCALE/2 + 20);
    }
    [UIView animateWithDuration:0.35 animations:^{
        shareBackView.frame = CGRectMake(0, SCREEN_HEIGHT-shareBackView.frame.size.height, shareBackView.frame.size.width, shareBackView.frame.size.height);
    }];
}
-(void)removeShareView{
//    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIWindow *window = [TMShareData shareData].window;
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
    UIView *blackView = [window viewWithTag:60000];
    UIView *shareView = [window viewWithTag:60001];
    shareView.frame =CGRectMake(0, shareView.frame.origin.y, shareView.frame.size.width, shareView.frame.size.height);
    [UIView animateWithDuration:0.35 animations:^{
        shareView.frame = CGRectMake(0, SCREEN_HEIGHT, shareView.frame.size.width, shareView.frame.size.height);
    } completion:^(BOOL finished) {
        
        [shareView removeFromSuperview];
        [blackView removeFromSuperview];
    }];
}

-(void)shareItemAction:(UIButton *)button {
//    [self removeShareView];
//    __weak typeof(self) weakSelf = self;
//    switch (button.tag) {
//        case 2000:
//            [weakSelf shareWebPageToPlatformType:UMSocialPlatformType_QQ];
//            break;
//        case 2001:
//            [weakSelf shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
//            break;
//        case 2002:
//            [weakSelf shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
//            break;
//        case 2003:
//            [weakSelf shareWebPageToPlatformType:UMSocialPlatformType_Qzone];
//            break;
//        case 2004:
//            [weakSelf shareWebPageToPlatformType:UMSocialPlatformType_Sina];
//            break;
//    }
}

//- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
//{
//    kWeakSelf(weakSelf)
//    //创建分享消息对象
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//    NSString * thumbURL = @"";
//    
//    // 将链接转译为UTF8因为 codeStr中有中文会导致QQ分享链接出错
//    NSString* encodedString = [thumbURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    
//    SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
//    [downloader downloadImageWithURL:[NSURL URLWithString:@""]
//                             options:0
//                            progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//                                // progression tracking code
//                            }
//                           completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
//                               if (image && finished) {
//                                   // do something with image
//                                   UMShareWebpageObject  *shareObject  = [UMShareWebpageObject shareObjectWithTitle:@""
//                                                                                                              descr:@""
//                                                                                                          thumImage:image];
//                                   //设置网页地址
//                                   shareObject.webpageUrl = encodedString;
//                                   
//                                   //分享消息对象设置分享内容对象
//                                   messageObject.shareObject = shareObject;
//                               }
//                               // 切换到主线程
//                               dispatch_async(dispatch_get_main_queue(), ^{
//                                   //调用分享接口
//                                   [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:weakSelf completion:^(id data, NSError *error) {
//                                       if (error) {
//                                           UMSocialLogInfo(@"************Share fail with error %@*********",error);
//                                           [weakSelf showHint:@"分享失败"];
//                                           
//                                       }else{
//                                           if ([data isKindOfClass:[UMSocialShareResponse class]]) {
//                                               UMSocialShareResponse *resp = data;
//                                               //分享结果消息
//                                               UMSocialLogInfo(@"response message is %@",resp.message);
//                                               //第三方原始返回的数据
//                                               UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
//                                               [weakSelf showHint:@"分享成功"];
//                                               
//                                           }else{
//                                               [weakSelf showHint:@"分享成功"];
//                                               UMSocialLogInfo(@"response data is %@",data);
//                                           }
//                                       }
//                                       
//                                   }];
//                               });
//                           }];
//    
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
